import React from 'react'

// 组件销毁时清除定时器
// 1. 先实现一个定时器小按钮 count 每隔1s + 1
// 2. 组件销毁时清除这个定制器


class Son extends React.Component{
  state = {
    count: 0
  }

  timer = null

  componentDidMount(){
    this.timer = setInterval(() => {
      console.log('定时器更新了');
      this.setState({
        count: this.state.count + 1
      })
    }, 1000);
  }

  componentWillUnmount(){
    clearInterval(this.timer)
  }
  render(){
    return <div>this is son {this.state.count}</div>
  }
}

class App extends React.Component {
  constructor(){
    console.log('constructor');
    super()
  }

  state = {
    flag: true
  }

  onChange = ()=>{
    this.setState({
      flag: false
    })
  }

  render () {
    return (
      <div>
        {/* 这里的flag如果是false Son组件就会被销毁 */}
        { this.state.flag ? <Son/>:null }
        <button onClick={ this.onChange }>change</button>
      </div>
    )
  }
}

export default App